/*
* CourseRegisterServiceImpl.java
* Created on  2014-5-7 下午5:24
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-5-7       gaoxinyu    初始版本
*
*/
package com.genghis.ptas.course.service.impl;

import com.genghis.core.page.entity.Page;
import com.genghis.core.page.entity.PageParameter;
import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.course.dao.CourseDao;
import com.genghis.ptas.course.dao.CourseRegisterDao;
import com.genghis.ptas.course.entity.ChapterInfo;
import com.genghis.ptas.course.entity.ChapterRegister;
import com.genghis.ptas.course.entity.CourseInfo;
import com.genghis.ptas.course.entity.CourseRegister;
import com.genghis.ptas.course.service.CourseRegisterService;
import com.genghis.ptas.course.service.CourseStatisticsService;
import com.genghis.ptas.note.entity.Note;
import com.genghis.ptas.note.service.NoteService;
import com.genghis.ptas.security.dao.UserDao;
import com.genghis.ptas.statistic.entity.CourseStatistics;
import com.genghis.ptas.system.service.DictService;
import com.genghis.ptas.util.DateUtil;
import com.genghis.ptas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类的描述信息
 *
 * @author fengxuanzhen
 * @version 1.0.1
 */
@Service("courseRegisterService")
public class CourseRegisterServiceImpl implements CourseRegisterService {

    @Autowired
    private CourseRegisterDao courseRegisterDao;

    @Autowired
    private DictService dictService;

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private NoteService noteService;

    @Autowired
    private CourseStatisticsService courseStatisticsService;

    @Override
    public Page<CourseRegister> findCourseRegisterPageList(PageParameter pageParameter, CourseRegister courseRegister) {
        Page<CourseRegister> coursePage = courseRegisterDao.findCourseRegisterPageList(pageParameter, courseRegister);
        for (CourseRegister courseRegisterTemp : coursePage.getResultList()) {
            courseRegisterTemp.setShowState(dictService.changeDictCodeToValue(courseRegisterTemp.getState(), DictConstant.STUDY_STATE));
        }
        return coursePage;
    }

    @Override
    public CourseRegister findCourseRegisterById(Integer id) {
        return courseRegisterDao.findCourseRegisterById(id);
    }

    @Override
    public List<CourseRegister> findCourseRegisterByCourseIdAndUserId(Integer courseId) {
        String loginName = LoginUserUtil.findLoginUserName();
        if (loginName == null) {
            return null;
        }
        Integer userId = userDao.findUserByLoginName(loginName).getId();
        List<CourseRegister> courseRegister = courseRegisterDao.findCourseRegisterByCourseIdAndUserId(courseId, userId);
        for (CourseRegister courseRegisterTemp : courseRegister) {
            courseRegisterTemp.setShowState(dictService.changeDictCodeToValue(courseRegisterTemp.getState(), DictConstant.STUDY_STATE));
            courseRegisterTemp.setScore(courseRegisterTemp.getScore()==null?"无":courseRegisterTemp.getScore());
        }
        return courseRegister;
    }

    @Override
    public List<ChapterRegister> findCourseChapterRegisterByCourseIdAndUserId(Integer id) {
        Integer userId = userDao.findUserByLoginName(LoginUserUtil.findLoginUserName()).getId();
        List<ChapterRegister> chapterRegisterList = courseRegisterDao.findCourseChapterRegisterByCourseIdAndUserId(id, userId);
        for (ChapterRegister chapterRegister : chapterRegisterList) {
            chapterRegister.setLessonStatus(translateLessonStatus(chapterRegister.getLessonStatus()));
        }
        return chapterRegisterList;
    }

    private String translateLessonStatus(String lessonStatus) {
        if (lessonStatus.equals(DictConstant.NOTATTEMPTED)) {
            return DictConstant.NOTATTEMPTED_TRANSLATION;
        }
        else if (lessonStatus.equals(DictConstant.INCOMPLETE)) {
            return DictConstant.INCOMPLETE_TRANSLATION;
        }
        else if (lessonStatus.equals(DictConstant.COMPLETE)) {
            return DictConstant.COMPLETE_TRANSLATION;
        }
        else {
            return DictConstant.NOTATTEMPTED_TRANSLATION;
        }
    }

    @Override
    public ChapterRegister findCourseChapterRegisterById(Integer id) {
        return courseRegisterDao.findCourseChapterRegisterById(id);
    }

    @Override
    public void editCourseChapterRegister(ChapterRegister chapterRegister) {
        CourseRegister courseRegister = courseRegisterDao.findCourseRegisterById(findCourseChapterRegisterById(chapterRegister.getId()).getCourseRegisterId());
//        courseStatisticsService.findCourseStatisticsByCourseId(courseRegister.getCourseId());
        if (chapterRegister.getJudgeFinal() == 1) {
            //修改注册课件表信息
            chapterRegister.setTotalTime(getTotalTime(chapterRegister.getTotalTime(), chapterRegister.getSessionTime()));
            courseRegister.setLastTime(chapterRegister.getSessionTime());
            courseRegister.setState(judgeCourseRegisterState(courseRegister.getId()));
            courseRegister.setTotalTime(getTotalTime(courseRegister.getTotalTime(), chapterRegister.getSessionTime()));
            courseRegisterDao.editCourseRegister(courseRegister);
            chapterRegister.setSessionTime("");
            //第一次看时给数据赋予默认值
            if (chapterRegister.getEntry() == null) {
                chapterRegister.setEntry(findCourseChapterRegisterById(chapterRegister.getId()).getEntry());
            }
            if (chapterRegister.getSessionTime() == null && chapterRegister.getTotalTime() == null) {
                getDefaultValues(chapterRegister);
            }
            //带测试题的章节判断当前章节是否为通过状态
            if (!chapterRegister.getTestStatus().equals("") && chapterRegister.getTestStatus() != null) {
                chapterRegister.setLessonStatus(chapterRegister.getTestStatus());
            }
            courseRegisterDao.editCourseChapterRegister(chapterRegister);
        }
    }

    private Integer judgeCourseRegisterState(Integer id) {
        List<ChapterRegister> chapterInfoList = courseRegisterDao.findCourseChapterRegisterByCourseRegisterId(id);
        for (ChapterRegister chapterRegister : chapterInfoList) {
            if (chapterRegister.getLessonStatus().equals(DictConstant.INCOMPLETE) || chapterRegister.getLessonStatus().equals(DictConstant.NOTATTEMPTED)) {
                return DictConstant.STUDY_STATE_1;
            }
        }
        return DictConstant.STUDY_STATE_2;
    }

    private void getDefaultValues(ChapterRegister chapterRegister) {
        chapterRegister.setSuspendData("");
        chapterRegister.setSuspendData("");
        chapterRegister.setTotalTime("");
        chapterRegister.setLessonLocation("");
        chapterRegister.setLessonMode("normal");
        chapterRegister.setCoreExit("");
    }

    private String getTotalTime(String totalTime, String sessionTime) {
        if (!totalTime.equals("") && !sessionTime.equals("")) {
            int mss = Integer.parseInt(totalTime.substring(11)) + Integer.parseInt(sessionTime.substring(11));
            int ms = mss % 100;
            int seconds = Integer.parseInt(totalTime.substring(8, 10)) + Integer.parseInt(sessionTime.substring(8, 10)) + mss / 100;
            int second = (seconds) % 60;
            int minutes = Integer.parseInt(totalTime.substring(5, 7)) + Integer.parseInt(sessionTime.substring(5, 7)) + seconds / 60;
            int minute = (minutes) % 60;
            int hours = Integer.parseInt(totalTime.substring(0, 4)) + Integer.parseInt(sessionTime.substring(0, 4)) + minutes / 60;
            String hour = "0000" + hours;
            String minuteForm = "00" + minute;
            String secondForm = "00" + second;
            String msForm = "00" + ms;
            return hour.substring(hour.length() - 4, hour.length()) + ":" + minuteForm.substring(minuteForm.length() - 2, minuteForm.length()) + ":" + secondForm.substring(secondForm.length() - 2, secondForm.length()) + "." + msForm.substring(msForm.length() - 2, msForm.length());
        }
        if (totalTime.equals("") && !sessionTime.equals("")) {
            return sessionTime;
        }
        if (!totalTime.equals("") && sessionTime.equals("")) {
            return totalTime;
        }
        return "";
    }

    @Override
    public void editCourseRegister(CourseRegister courseRegister) {
        courseRegisterDao.editCourseRegister(courseRegister);
    }

    @Override
    public void deleteCourseRegisterById(Integer id) {
        courseRegisterDao.deleteCourseRegisterById(id);
    }

    @Override
    public int addCourseRegister(CourseRegister courseRegister) {
        Integer userId = userDao.findUserByLoginName(LoginUserUtil.findLoginUserName()).getId();
        //新增笔记
        CourseInfo courseInfo = courseDao.findCourseByCourseId(courseRegister.getCourseId());
        int noteId = noteService.addNote(new Note("", courseInfo.getCourseName() + DateUtil.getSystemDate("yyyy-MM-dd HH:mm:ss"), courseInfo.getCourseType(), 0));
        //新增课件注册
        courseRegister.setNoteId(noteId);
        courseRegister.setStudentId(userId);
        courseRegister.setState(DictConstant.STUDY_STATE_0);
        courseRegister.setRegisterDate(DateUtil.getSystemDate(DictConstant.DATE_FORMAT));
        int courseRegisterId = courseRegisterDao.addCourseRegister(courseRegister);
        //新增注册章节信息
        List<ChapterInfo> chapterInfoList = courseDao.findChapterByCourseId(courseRegister.getCourseId());
        for (ChapterInfo chapterInfo : chapterInfoList) {
            ChapterRegister chapterRegister = new ChapterRegister();
            chapterRegister.setCourseChapterId(chapterInfo.getId());
            chapterRegister.setCourseRegisterId(courseRegisterId);
            chapterRegister.setLessonStatus("notattempted");
            chapterRegister.setStudentId(userId);
            chapterRegister.setNoteId(noteId);
            courseRegisterDao.addCourseChapterRegister(chapterRegister);
        }
        //修改统计信息
        CourseStatistics courseStatistics = courseStatisticsService.findCourseStatisticsByCourseId(courseInfo.getId());
        courseStatistics.setRegisterNumber(courseStatistics.getRegisterNumber() + 1);
        courseStatisticsService.editCourseStatistics(courseStatistics);
        return courseRegisterId;
    }

    @Override
    public Boolean checkWhetherRegisterByCourseId(Integer id) {
        List<CourseRegister> courseRegisterList = findCourseRegisterByCourseIdAndUserId(id);
        if (courseRegisterList == null) {
            return true;
        }
        return courseRegisterList.size() == 0;
    }

    @Override
    public List<CourseRegister> findCourseRegisterByUserId(Integer userId) {
        List<CourseRegister> courseRegisterList = courseRegisterDao.findCourseRegisterByUserId(userId);
        for (CourseRegister courseRegister : courseRegisterList) {
            courseRegister.setShowState(dictService.changeDictCodeToValue(courseRegister.getState(), DictConstant.STUDY_STATE));
        }
        return courseRegisterList;
    }

}
